from io import BytesIO
from xml.dom import minidom
import xml.etree.ElementTree as ET


# 生成格式化的 XML 字符串
def generate_formatted_xml(code: str, message: str, resource: str):
    r"""
    生成格式化的 XML 字符串
    :param code: <Code>NoSuchBucket</Code> 中的 NoSuchBucket
    :param message: <Message>The specified bucket does not exist</Message> 中的 The specified bucket does not exist
    :param resource: <Resource>mybucket</Resource> 中的 mybucket
    :return: 格式化的 XML 字符串
    ps:
        <?xml version="1.0" encoding="UTF-8"?>
        <Error>
            <Code>NoSuchBucket</Code>
            <Message>The specified bucket does not exist</Message>
            <Resource>mybucket</Resource>
        </Error>
    """
    # 创建根元素
    error = ET.Element("Error")

    # 添加子元素
    code_elem = ET.SubElement(error, "Code")
    code_elem.text = code

    message_elem = ET.SubElement(error, "Message")
    message_elem.text = message

    resource_elem = ET.SubElement(error, "Resource")
    resource_elem.text = resource

    # 使用 BytesIO 来捕获输出
    output = BytesIO()
    tree = ET.ElementTree(error)
    tree.write(output, xml_declaration=True, encoding='UTF-8')

    # 获取 XML 字符串并美化
    xml_bytes = output.getvalue()
    xml_string = xml_bytes.decode('UTF-8')
    pretty_xml_string = minidom.parseString(xml_string).toprettyxml(indent="    ", encoding='UTF-8').decode('UTF-8')

    # 关闭 BytesIO
    output.close()

    return pretty_xml_string


# 规范化object 名称
def normalize_object_name(bucket: str, object_key: str) -> str:
    """
    规范化 object_key 名称 就是如果 是 {bucket}/{object_key} 或者 {bucket}\{object_key} 或者 /{object_key} 或者 \{object_key} 形式的  只保留 object_key
    :param bucket: 桶名
    :param object_key: 对象名
    :return: 规范化后的对象名
    """
    if object_key.startswith(bucket):
        object_key = object_key[len(bucket):]
    if object_key.startswith("/") or object_key.startswith("\\"):
        object_key = object_key[1:]
    return object_key
